package com.kidedu.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.kidedu.entity.KAdmin;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class AdminLoginInterceptor  implements Interceptor{
	public static Log log = LogFactory.getLog(AdminLoginInterceptor.class);
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void init() {
		// TODO Auto-generated method stub
		
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		  ActionContext.getContext().getSession().put("ctx", ServletActionContext.getServletContext().getContextPath());
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		session = request.getSession();
		String retUrl = request.getHeader("Referer");
		if (isAjaxRequest()) {
			session.setAttribute("afterLoginUrl", retUrl);
			return ajaxIntercept(invocation);
		}
		return generalIntercept(invocation);
	}
	// 普通请求拦截 没登录返回 noLogin 登录流程继续
		private String generalIntercept(ActionInvocation invocation) throws Exception {
		
			KAdmin admin=(KAdmin)session.getAttribute("ADMIN");
			
			if(null==admin)
			{
				response.setContentType("text/html");
				response.getWriter().print("未登录");
				return "NoLogin";
			}
			return invocation.invoke();
		}
		
		// ajax请求拦截 没登录返回 NoLogin 登录流程继续
		private String ajaxIntercept(ActionInvocation invocation) throws Exception {
			
		
			KAdmin admin=(KAdmin)session.getAttribute("ADMIN");
		
			if(null==admin)
			{
				response.setContentType("text/html");
				response.getWriter().print("No_Loading");
				return null;
			}
			return invocation.invoke();
		}
		//判断是否为ajax请求
		private boolean isAjaxRequest() {
			String header = request.getHeader("X-Requested-With");
			if (header != null && "XMLHttpRequest".equals(header)) {
				return true;
			}
			return false;
		}
}
